package order

import (
	"fmt"
	"github.com/gin-gonic/gin"
	ut "github.com/go-playground/universal-translator"
	proto "goTong/api/order/v1"
	"goTong/app/hlw/api/internal/domain/request"
	"goTong/app/hlw/api/internal/service"
	gin2 "goTong/app/pkg/translator/gin"
	"goTong/gtong/server/restserver/middlewares"
	"goTong/pkg/log"
	"math/rand"
	"net/http"
	"time"
)

type orderController struct {
	srv   service.ServiceFactory
	trans ut.Translator
}

func NewOrderController(srv service.ServiceFactory, trans ut.Translator) *orderController {
	return &orderController{srv: srv, trans: trans}
}
func generateOrderSn(userId int32) string {
	//订单号的生成规则
	/*
		年月日时分秒+用户id+2位随机数
	*/
	now := time.Now()
	rand.New(rand.NewSource(time.Now().UnixNano()))
	orderSn := fmt.Sprintf("%d%d%d%d%d%d%d%d",
		now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute(), now.Nanosecond(),
		userId, rand.Intn(90)+10,
	)
	return orderSn
}
func (od *orderController) SubmitOrder(ctx *gin.Context) {
	log.Info("order submit funciont called ...")
	userID, _ := ctx.Get(middlewares.KeyUserID)
	var r request.OrderFilter
	if err := ctx.ShouldBindQuery(&r); err != nil {
		gin2.HandleValidatorError(ctx, err, od.trans)
		return
	}
	gfr := proto.OrderRequest{
		UserId:  userID.(int32),
		Address: r.Address,
		OrderSn: generateOrderSn(12),
		Name:    r.Name,
		Post:    r.Post,
		Mobile:  r.Mobile,
	}
	err := od.srv.Order().SubmitOrder(ctx, &gfr)
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{
			"msg": "新建订单失败",
		})
		return
	}
	fmt.Println("订单新建成功")
	ctx.JSON(http.StatusOK, gin.H{
		"orderSn": gfr.OrderSn,
	})
}
